package com.miracle.anychatdemo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bairuitech.anychat.AnyChatBaseEvent;
import com.bairuitech.anychat.AnyChatCoreSDK;
import com.bairuitech.anychat.AnyChatDefine;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  多人视频聊天界面
 */
public class MultiVideoChatActivity extends Activity implements AnyChatBaseEvent {

	private final int UPDATEVIDEOBITDELAYMILLIS = 200; //监听音频视频的码率的间隔刷新时间（毫秒）
	
	int userID;
	/**所有用户id*/
	List<Integer> mUserIds = new ArrayList<>();

	/**所有userId对应的位置*/
	Map<Integer,Integer> mUserPoses = new HashMap();
	/**所有userId对应的视图*/
	Map<Integer,SurfaceView> mUserViews = new HashMap();

	private boolean bSelfVideoOpened = false; // 本地视频是否已打开
	private boolean bOtherVideoOpened = false; // 对方视频是否已打开
	private Boolean mFirstGetVideoBitrate = false; //"第一次"获得视频码率的标致
	private Boolean mFirstGetAudioBitrate = false; //"第一次"获得音频码率的标致

	private StateChangedButton mImgSwitchVideo;
	private StateChangedButton mEndCallBtn;
//	private ImageView mBtnCameraCtrl; // 控制视频的按钮
	private ImageView mBtnSpeakCtrl; // 控制音频的按钮


	public AnyChatCoreSDK mAnychatSDK;


	FluidLayout mLayouts;

	/*当前放大的位置*/
	int mCurrentScalePos = -1;
	/**被放大的视图*/
	private SurfaceView mScaleSurfaceView;
	private RelativeLayout mRootLayout;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);



		InitSDK();
		initData();
		InitLayout();

		// 如果视频流过来了，则把背景设置成透明的//每0.2秒执行一次
		handler.postDelayed(runnable, UPDATEVIDEOBITDELAYMILLIS);
	}

	private void initData() {
		Intent intent = getIntent();
//		userID = Integer.parseInt(intent.getStringExtra("UserID"));
		String[] userIdsStr = intent.getStringArrayExtra("userIds");
		for (String userIdStr :
				userIdsStr) {
			mUserIds.add(Integer.parseInt(userIdStr));
		}
	}

	private void InitSDK() {
		mAnychatSDK = AnyChatCoreSDK.getInstance(this);
		mAnychatSDK.SetBaseEvent(this);
		mAnychatSDK.mSensorHelper.InitSensor(getApplicationContext());
		AnyChatCoreSDK.mCameraHelper.SetContext(getApplicationContext());
	}

	private void InitLayout() {
		this.setContentView(R.layout.activity_videochat_multi);

		String title = initTitle();

		this.setTitle("与 \"" + title + "\" 对话中");
		mLayouts = findViewById(R.id.mLayouts);

		MultiVideoChatInfo myInfo = new MultiVideoChatInfo();
		myInfo.setPosition(0);
		myInfo.setUserId("-1");
		List<MultiVideoChatInfo> infos = new ArrayList<>();
		infos.add(myInfo);

		addChildSurfaceView(myInfo);

		mImgSwitchVideo = (StateChangedButton) findViewById(R.id.ImgSwichVideo);
		mEndCallBtn = (StateChangedButton) findViewById(R.id.endCall);
		mBtnSpeakCtrl = (ImageView) findViewById(R.id.btn_speakControl);
		mRootLayout = findViewById(R.id.mRootLayout);



//		mBtnCameraCtrl = (ImageView) findViewById(R.id.btn_cameraControl);
		mBtnSpeakCtrl.setOnClickListener(onClickListener);
//		mBtnCameraCtrl.setOnClickListener(onClickListener);
		mImgSwitchVideo.setOnClickListener(onClickListener);
		mEndCallBtn.setOnClickListener(onClickListener);



		mAnychatSDK.UserCameraControl(-1, 1);// -1表示对本地视频进行控制，打开本地视频
		mAnychatSDK.UserSpeakControl(-1, 1);// -1表示对本地音频进行控制，打开本地音频

	}


	/**
	 *  初始化标题
	 * @return
	 */
	private String initTitle() {
		StringBuilder sb = new StringBuilder();
		int i = 0;
		for (int userId :
				mUserIds) {
			if (i != 0) sb.append("、");
			sb.append(mAnychatSDK.GetUserName(userId));
			i++;
		}
		return sb.toString();
	}

	Handler handler = new Handler();
	Runnable runnable = new Runnable() {

		@Override
		public void run() {
//			for (int userId :
//					mUserIds) {
//				try {
//					int videoBitrate = mAnychatSDK.QueryUserStateInt(userId,
//							AnyChatDefine.BRAC_USERSTATE_VIDEOBITRATE);
//					int audioBitrate = mAnychatSDK.QueryUserStateInt(userId,
//							AnyChatDefine.BRAC_USERSTATE_AUDIOBITRATE);
//					if (videoBitrate > 0)
//					{
//						//mHandler.removeCallbacks(runnable);
//						mFirstGetVideoBitrate = true;
////						SurfaceView otherView = mUserViews.get(userId);
////						otherView.setBackgroundColor(Color.TRANSPARENT);
////						mOtherView.setBackgroundColor(Color.TRANSPARENT);
//					}
//
//					if(audioBitrate > 0){
//						mFirstGetAudioBitrate = true;
//					}
//
//					String userName = mAnychatSDK.GetUserName(userId);
//					if (mFirstGetVideoBitrate)
//					{
//						if (videoBitrate <= 0){
//							Toast.makeText(MultiVideoChatActivity.this, userName+"视频中断了!", Toast.LENGTH_SHORT).show();
//							// 重置下，如果对方退出了，有进去了的情况
//							mFirstGetVideoBitrate = false;
//						}
//					}
//
//					if (mFirstGetAudioBitrate){
//						if (audioBitrate <= 0){
//							Toast.makeText(MultiVideoChatActivity.this, userName+"音频中断了!", Toast.LENGTH_SHORT).show();
//							// 重置下，如果对方退出了，有进去了的情况
//							mFirstGetAudioBitrate = false;
//						}
//					}
//
//					handler.postDelayed(runnable, UPDATEVIDEOBITDELAYMILLIS);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//
//			}

		}
	};


	private void  addChildSurfaceView(MultiVideoChatInfo info){
		addChildSurfaceView(info,-1);
	}

	/**
	 * 根据位置插入用户视图
	 * @param info
	 * @param pos
	 */
	private void addChildSurfaceView(final MultiVideoChatInfo info, int pos){
		final SurfaceView surfaceView = new SurfaceView(this);
		FluidLayout.LayoutParams params = new FluidLayout.LayoutParams(ScreenUtils.getScreenWidth(this)/4,
				ScreenUtils.getScreenWidth(this)/4);

		params.setMargins(12,12,12,12);
		surfaceView.setLayoutParams(params);
		final String userId = info.getUserId();

		final int bindIndex = bindSurfaceView(userId, surfaceView);


		final int currentPos = bindIndex+1;

		mUserPoses.put(Integer.valueOf(userId),currentPos);
		mUserViews.put(Integer.valueOf(userId),surfaceView);

		surfaceView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				if (userId.equals("-1")){
					AnyChatCoreSDK.mCameraHelper.CloseCamera();
					mAnychatSDK.UserCameraControl(-1, 0);
					mAnychatSDK.UserSpeakControl(-1, 0);
				}else {
					mAnychatSDK.mVideoHelper.UnBindVideo(bindIndex);
					mAnychatSDK.UserCameraControl(Integer.valueOf(userId), 0);
					mAnychatSDK.UserSpeakControl(Integer.valueOf(userId), 0);
				}

				mLayouts.removeView(surfaceView);
				mCurrentScalePos = currentPos;

				mScaleSurfaceView = new SurfaceView(MultiVideoChatActivity.this);
				ViewGroup.LayoutParams scaleParams =new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
						ScreenUtils.getScreenHeight(MultiVideoChatActivity.this)/2);
				mScaleSurfaceView.setLayoutParams(scaleParams);

				//视图置顶
				mScaleSurfaceView.setZOrderOnTop(true);
				mScaleSurfaceView.setZOrderMediaOverlay(true);

				mRootLayout.addView(mScaleSurfaceView);
				mScaleSurfaceView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						mRootLayout.removeView(mScaleSurfaceView);
						addChildSurfaceView(info,mCurrentScalePos);
					}
				});
				bindSurfaceView(userId,mScaleSurfaceView);

				if (userId.equals("-1")){
					mAnychatSDK.UserCameraControl(-1, 1);
					mAnychatSDK.UserSpeakControl(-1, 1);
				}else {
					mAnychatSDK.UserCameraControl(Integer.valueOf(userId), 1);
					mAnychatSDK.UserSpeakControl(Integer.valueOf(userId), 1);
				}

			}
		});

		if (pos != -1){
			try {
				mLayouts.addView(surfaceView,pos);
			} catch (Exception e) {
				e.printStackTrace();
				mLayouts.addView(surfaceView);
			}
		}else {
			mLayouts.addView(surfaceView);
		}
	}


	/**
	 * 绑定视图
	 * @param userId
	 * @param surfaceView
	 */
	private int bindSurfaceView(String userId ,SurfaceView surfaceView){

		int bindIndex = -1;
		if (userId.equals("-1")){    //初始化本地视频

			// 如果是采用Java视频采集，则需要设置Surface的CallBack
			if (AnyChatCoreSDK
					.GetSDKOptionInt(AnyChatDefine.BRAC_SO_LOCALVIDEO_CAPDRIVER) == AnyChatDefine.VIDEOCAP_DRIVER_JAVA) {
				surfaceView.getHolder().addCallback(AnyChatCoreSDK.mCameraHelper);
			}



			// 判断是否显示本地摄像头切换图标
			if (AnyChatCoreSDK
					.GetSDKOptionInt(AnyChatDefine.BRAC_SO_LOCALVIDEO_CAPDRIVER) == AnyChatDefine.VIDEOCAP_DRIVER_JAVA) {
				if (AnyChatCoreSDK.mCameraHelper.GetCameraNumber() > 1) {
					// 默认打开前置摄像头
					AnyChatCoreSDK.mCameraHelper
							.SelectVideoCapture(AnyChatCoreSDK.mCameraHelper.CAMERA_FACING_FRONT);
				}
			} else {
				String[] strVideoCaptures = mAnychatSDK.EnumVideoCapture();
				if (strVideoCaptures != null && strVideoCaptures.length > 1) {
					// 默认打开前置摄像头
					for (int i = 0; i < strVideoCaptures.length; i++) {
						String strDevices = strVideoCaptures[i];
						if (strDevices.indexOf("Front") >= 0) {
							mAnychatSDK.SelectVideoCapture(strDevices);
							break;
						}
					}
				}
			}

		}else {
			if (AnyChatCoreSDK
					.GetSDKOptionInt(AnyChatDefine.BRAC_SO_VIDEOSHOW_DRIVERCTRL) == AnyChatDefine.VIDEOSHOW_DRIVER_JAVA) {
				int index = mAnychatSDK.mVideoHelper.bindVideo(surfaceView
						.getHolder());
				mAnychatSDK.mVideoHelper.SetVideoUser(index, Integer.parseInt(userId));
				bindIndex = index;
			}
		}
		return bindIndex;
	}


	private void removeChildSurfaceView(int userId){
		SurfaceView surfaceView = mUserViews.get(userId);
		mLayouts.removeView(surfaceView);
	}

	private OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case (R.id.ImgSwichVideo): {

				// 如果是采用Java视频采集，则在Java层进行摄像头切换
				if (AnyChatCoreSDK
						.GetSDKOptionInt(AnyChatDefine.BRAC_SO_LOCALVIDEO_CAPDRIVER) == AnyChatDefine.VIDEOCAP_DRIVER_JAVA) {
					AnyChatCoreSDK.mCameraHelper.SwitchCamera();
					return;
				}

				String strVideoCaptures[] = mAnychatSDK.EnumVideoCapture();
				String temp = mAnychatSDK.GetCurVideoCapture();
				for (int i = 0; i < strVideoCaptures.length; i++) {
					if (!temp.equals(strVideoCaptures[i])) {
						mAnychatSDK.UserCameraControl(-1, 0);
						bSelfVideoOpened = false;
						mAnychatSDK.SelectVideoCapture(strVideoCaptures[i]);
						mAnychatSDK.UserCameraControl(-1, 1);
						break;
					}
				}
			}
				break;
			case (R.id.endCall): {
				exitVideoDialog();
				break;
			}
			case R.id.btn_speakControl:
				if ((mAnychatSDK.GetSpeakState(-1) == 1)) {
					mBtnSpeakCtrl.setImageResource(R.drawable.ic_voipvoicebanoff);
					mAnychatSDK.UserSpeakControl(-1, 0);
				} else {
					mBtnSpeakCtrl.setImageResource(R.drawable.ic_voipvoicebanon);
					mAnychatSDK.UserSpeakControl(-1, 1);
				}
				break;
			case R.id.btn_cameraControl:
				if ((mAnychatSDK.GetCameraState(-1) == 2)) {
//					mBtnCameraCtrl.setImageResource(R.drawable.camera_off);
					mAnychatSDK.UserCameraControl(-1, 0);
				} else {
//					mBtnCameraCtrl.setImageResource(R.drawable.camera_on);
					mAnychatSDK.UserCameraControl(-1, 1);
				}
				break;
			default:
				break;
			}
		}
	};



	private void refreshAV() {
		for (int userId :
				mUserIds) {
			mAnychatSDK.UserCameraControl(userId, 1);
			mAnychatSDK.UserSpeakControl(userId, 1);
			mAnychatSDK.UserCameraControl(-1, 1);
			mAnychatSDK.UserSpeakControl(-1, 1);
//			mBtnSpeakCtrl.setImageResource(R.drawable.speak_on);
//		mBtnCameraCtrl.setImageResource(R.drawable.camera_on);
			bOtherVideoOpened = false;
			bSelfVideoOpened = false;
		}
	}

	private void exitVideoDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("是否退出视频聊天？")
				.setCancelable(false)
				.setPositiveButton("确认",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								destroyCurActivity();
							}
						})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				}).show();
	}

	private void destroyCurActivity() {
		onPause();
		onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exitVideoDialog();
		}

		return super.onKeyDown(keyCode, event);
	}

	protected void onRestart() {
		super.onRestart();

	}

	protected void onResume() {
		super.onResume();
	}

	protected void onPause() {
		super.onPause();

	}

	protected void onDestroy() {
		super.onDestroy();
		handler.removeCallbacks(runnable);
		mAnychatSDK.removeEvent(this);
		mAnychatSDK.mSensorHelper.DestroySensor();
		finish();
	}



	@Override
	public void OnAnyChatConnectMessage(boolean bSuccess) {

	}

	@Override
	public void OnAnyChatLoginMessage(int dwUserId, int dwErrorCode) {

	}

	@Override
	public void OnAnyChatEnterRoomMessage(int dwRoomId, int dwErrorCode) {

	}

	@Override
	public void OnAnyChatOnlineUserMessage(int dwUserNum, int dwRoomId) {

	}

	@Override
	public void OnAnyChatUserAtRoomMessage(int dwUserId, boolean bEnter) {
		if (!bEnter) {
			String userName = mAnychatSDK.GetUserName(dwUserId);
				Toast.makeText(MultiVideoChatActivity.this, userName+"已离开！", Toast.LENGTH_SHORT).show();
				mAnychatSDK.UserCameraControl(dwUserId, 0);
				mAnychatSDK.UserSpeakControl(dwUserId, 0);
				bOtherVideoOpened = false;


				removeChildSurfaceView(dwUserId);
				if (mUserPoses.size()>0 && mUserPoses.containsKey(dwUserId)){
					int userPos = mUserPoses.get(dwUserId);
					mAnychatSDK.mVideoHelper.UnBindVideo(userPos);
				}

		} else {

			mUserIds.add(dwUserId);         //添加新进房间的视图

			MultiVideoChatInfo info = new MultiVideoChatInfo();
			info.setUserId(String.valueOf(dwUserId));

			addChildSurfaceView(info);


			mAnychatSDK.UserCameraControl(dwUserId, 1);
			mAnychatSDK.UserSpeakControl(dwUserId, 1);
		}
	}

	@Override
	public void OnAnyChatLinkCloseMessage(int dwErrorCode) {
		// 网络连接断开之后，上层需要主动关闭已经打开的音视频设备
		if (bOtherVideoOpened) {
			for (int userId :
					mUserIds) {
				mAnychatSDK.UserCameraControl(userId, 0);
				mAnychatSDK.UserSpeakControl(userId, 0);
			}
			bOtherVideoOpened = false;
		}
		if (bSelfVideoOpened) {
			mAnychatSDK.UserCameraControl(-1, 0);
			mAnychatSDK.UserSpeakControl(-1, 0);
			bSelfVideoOpened = false;
		}

		// 销毁当前界面
		destroyCurActivity();
		Intent mIntent = new Intent("VideoActivity");
		// 发送广播
		sendBroadcast(mIntent);
	}

}
